#pragma once
#include <string>
#include <sstream>
#include <fstream>
#include <iostream>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>

using namespace std;
const string sep = "\r\n";
const string default_dir = "./wwwspray_rain";
const string home_page = "index.html";
const string html_404 = "./wwwspray_rain/404.html";

class Util
{
public:
    // xxxxx xxx xxx\r\nxxx
    static string GetOneLine(string &inbuff, const string &sep)
    {
        auto pos = inbuff.find(sep);
        if (pos == string::npos)
            return "";
        string content = inbuff.substr(0, pos);
        inbuff.erase(0, content.size() + sep.size());
        return content;
    }

    static bool ReadFile(string resource, char *buff, int size)
    {
        ifstream in(resource, std::ios::binary);
        if (!in.is_open())
            return false;
        in.read(buff, size);
        return true;
    }
};

class http_request
{
public:
    http_request() {}
    ~http_request() {}

    void parse()
    {
        // 从缓冲区中读取一行完整的数据，去掉协议内容
        content = Util::GetOneLine(_inbuff, sep);
        if (content.empty())
            return;

        // 把这一行完整的请求行分解出三个字段
        // 这里有好用的工具 stringstream
        stringstream ss(content);
        ss >> _method >> _url >> _http_version;

        // 添加web默认路径
        _path = default_dir; //  ./www_spray_rain
        _path += _url;       // url解析默认为/...其它目录，我们只需要默认路径拼上url即可

        if (_path[_path.size() - 1] == '/')
            _path += home_page;

        // 获取path对应的资源后缀
        // ./wwwspray_rain/index.html
        // ./wwwspray_rain/test/a.html
        // ./wwwspray_rain/image/1.jpg
        auto pos = _path.rfind(".");
        if (pos == 0 || pos == string::npos)
            _suffix = ".html";
        else
            _suffix = _path.substr(pos);

        struct stat st;
        int check = stat(_path.c_str(), &st);
        if (check == 0)
            _size = st.st_size;
        else
        {
            stat(html_404.c_str(), &st);
            _size = st.st_size;
        }
    }

    string _inbuff;
    string _url;
    string _method;
    string _http_version;
    string _path;
    string _suffix;
    string content;
    string _body;
    int _size = -1;
};

class http_response
{
public:
    string _outbuff;
};